import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store/index';
import staticRoute from './staticRoute';

Vue.use(VueRouter);

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

const router = new VueRouter({
  routes: staticRoute,
});
let isBreak = true;
router.beforeEach(async (to, from, next) => {
  // isBreak为true和vuex不为空时添加路由;
  if (isBreak && store.state.routers.routers.length != 0) {
    //从vuex中获取动态路由
    const accessRouteses = await store.state.routers.routers;
    //动态路由循环解析和添加
    accessRouteses.forEach((v) => {
      v.children = routerChildren(v.children);
      v.component = routerCom(v.component);
      router.addRoute(v); //添加
    });
    //跳出循环
    isBreak = false;
    //确保addRoutes已完成
    next({ ...to, replace: true });
  } else {
    if (to.path == '/login') {
      isBreak = true;
      if (to.meta.title) {
        document.title = to.meta.title;
      }
      next();
    } else if (!store.state.routers.token) {
      if (to.meta.title) {
        document.title = to.meta.title;
      }
      return next('/login');
    } else {
      if (to.meta.title) {
        //判断是否有标题
        document.title = to.meta.title; //给相应页面添加标题
      }
      next();
    }
  }
});
function routerCom(component) {
  if (component === 'Home.vue') {
    return () => import(`@/views/${component}`);
  }
  return () => import(`@/pages/${component}`);
  // return (resolve) => require([`@/views/${path}`], resolve);
}
function routerChildren(children) {
  if (!children) return;
  children.forEach((v) => {
    v.children = routerChildren(v.children);
    v.component = routerCom(v.component);
  });
  return children;
}

//重置路由
export function resetRouter(router) {
  const createRouter = new VueRouter({
    routes: staticRoute,
  });
  // 用初始化的matcher替换当前router的matcher
  router.matcher = createRouter.matcher;
}

export default router;
